<?php
/**
 * Searches files from defined locations (paths). The paths are searched in LIFO order.
 * 
 * @category Lead
 * @package Lead_Tool
 * @subpackage File
 */
class Lead_Tool_File_Searcher
{
	/**
	 * Search locations (paths)
	 *
	 * @var array
	 */
	private $_paths = array();
		
	
	/**
	 * Clears the search paths
	 *
	 */
	function clearPaths()
	{
		$this->_paths = array();
	}
	
	
	public function hasPaths()
	{
	    return (sizeof($this->_paths) > 0) ? true : false;
	}
	
	/**
	 * Adds a path.
	 *
	 * @param string $path Path to be searched.
	 * 
	 */
	function addPath($path)
	{
	   $this->_paths[] = $path;
	}
	
	
	/**
	 * Returns all defined paths.
	 *
	 * @return array
	 */
	public function getPaths()
	{
	    return $this->_paths;
	}
	
	
	
	/**
	 * Searches a resource from paths defined. 
	 *
	 * @param string $resource Resource name
	 * @return string|false Found resource path on success, false on failure.
	 */
	public function find($resource)
	{					
		$returnResource = false;
		foreach(array_reverse($this->_paths) as $path)
		{
			$resourceName = $path . "/{$resource}";
			if($this->isMatch($resourceName))
			{
			    $returnResource = $resourceName;
				break;
			}
		}
	
		return $returnResource;
	}
	
	/**
	 * Returns true if a path is deemed a match, false if not.
	 *
	 * @param string $resourceName
	 * @return boolean
	 */
	protected function isMatch($resourceName)
	{
		return is_readable($resourceName);
	}
}
